package com.user.controller;

import com.bean.WmsTPermission;
import com.bean.WmsTStore;
import com.bean.WmsTTray;
import com.bean.WmsTUser;
import com.user.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("user")
public class MyController {

    @Autowired
    MyService myService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("left.do")
    public String left(){
        return "user/left";
    }

    @RequestMapping("top.do")
    public String top(){
        return "user/top";
    }

    @RequestMapping("load.do")
    public String load(HttpServletRequest request){
        List<WmsTPermission> wmsPermissions = myService.selectPer();
        request.getSession().setAttribute("wmspermissions",wmsPermissions);
        return "user/login";
    }

    @RequestMapping("login.do")
    public String login(WmsTUser wmsTUser,HttpServletRequest request,HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        Map<Object, Object> userss = stringRedisTemplate.opsForHash().entries("userss");
        WmsTUser wmsTUser2 = myService.load(wmsTUser);
        if (userss == null) {
            System.out.println("走数据库了");
            //查询数据库是否存在该人，如果不存在
            if (wmsTUser2 == null) {
                try {
                    response.getWriter().println("<script>alert('登录失败，请检查用户名或密码是否正确');window.location='http://localhost:10000/user/load.do'</script>");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                //改人存在于数据库 同时还要写入到redis
                System.out.println("写入到redis");
                stringRedisTemplate.opsForHash().put("userss",wmsTUser.getUserAccount(),wmsTUser.getUserPwd());
                if (wmsTUser.getPermName() != null && wmsTUser.getPermName().equals(wmsTUser2.getPermName())){
                    System.out.println("权限相同");
                    //判断缓存是否为空

                }else {
                    try {
                        response.getWriter().println("<script>alert('登录失败，用户权限错误');window.location='http://localhost:10000/user/load.do'</script>");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            for (Object a:userss.keySet()) {
                if (wmsTUser.getUserAccount().equals(a)) {
                    for (Object b:userss.values()) {
                        //如果相同 直接登录成功
                        if (wmsTUser.getUserPwd().equals(b)) {
                            System.out.println("redis相同");
                            if (wmsTUser.getPermName() != null && wmsTUser.getPermName().equals(wmsTUser2.getPermName())){
                                System.out.println("权限相同");
                                //判断缓存是否为空

                            }else {
                                try {
                                    response.getWriter().println("<script>alert('登录失败，用户权限错误');window.location='http://localhost:10000/user/load.do'</script>");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                } else {
                    //跟数据库比较
                    System.out.println("走数据库了");
                    WmsTUser wmsTUser1 = myService.load(wmsTUser);
                    //查询数据库是否存在该人，如果不存在
                    if (wmsTUser1 == null) {
                        try {
                            response.getWriter().println("<script>alert('登录失败，请检查用户名或密码是否正确');window.location='http://localhost:10000/user/load.do'</script>");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("写入到redis");
                        //改人存在于数据库 同时还要写入到redis
                        stringRedisTemplate.opsForHash().put("userss",wmsTUser.getUserAccount(),wmsTUser.getUserPwd());
                        if (wmsTUser.getPermName() != null && wmsTUser.getPermName().equals(wmsTUser2.getPermName())){
                            System.out.println("权限相同");
                            //判断缓存是否为空

                        }else {
                            try {
                                response.getWriter().println("<script>alert('登录失败，用户权限错误');window.location='http://localhost:10000/user/load.do'</script>");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }

        //把名字存进域
        request.getSession().setAttribute("load_user",wmsTUser2);
        return "user/admin";
    }
    //判断验证码
    @RequestMapping("checkcode.do")
        public void pdyzm(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("utf-8");// 处理post请求乱码问题
            response.setContentType("text/html;charset=utf-8"); // 处理响应乱码问题:字节流需getBytes("UTF-8")

            String yzm = request.getParameter("yzm");
            System.out.println(yzm);
            String yanzm1 = (String) request.getSession().getAttribute("checkcode");
            System.out.println(yanzm1);
            if(yzm.equals(yanzm1)){
                response.getWriter().print("true");
            }else {
                response.getWriter().print("false");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //生成验证码
    @RequestMapping("getcode.do")
    public void getCode(HttpServletRequest request, HttpServletResponse response){
        // gui 生成图片
        // 1 高和宽
        int height = 30;
        int width = 60;
        String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();

        // 2 创建一个图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 3 获得画板
        Graphics g = image.getGraphics();
        // 4 填充一个矩形
        // * 设置颜色
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, width, height);

        g.setColor(Color.WHITE);
        g.fillRect(1, 1, width - 2, height - 2);
        // * 设置字体
        g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 25));
        StringBuilder sb = new StringBuilder();// 获取验证码字符信息
        // 5 写随机字
        for (int i = 0; i < 4; i++) {
            // 设置颜色--随机数
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));

            // 获得随机字
            int index = random.nextInt(data.length());
            String str = data.substring(index, index + 1);
            sb.append(str);
            // 写入
            g.drawString(str, width / 6 * (i + 1), 20);

        }
        // 验证码保存到session对象中
        request.getSession().setAttribute("checkcode", sb.toString());

        // 6 干扰线
        for (int i = 0; i < 3; i++) {
            // 设置颜色--随机数
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            // 随机绘制先
            g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
            // 随机点
            g.drawOval(random.nextInt(width), random.nextInt(height), 2, 2);
        }

        // end 将图片响应给浏览器
        try {
            ImageIO.write(image, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("mingxi.do")
    public String mingxi(){
        return "user/usemingxi";
    }

    @RequestMapping("usemingxi.do")
    @ResponseBody
    public List<WmsTStore> usemingxi(){
        List<WmsTStore> wmsTStores = myService.selectStore();
        return wmsTStores;
    }

    @RequestMapping("usexiangqing.do")
    @ResponseBody
    public List<WmsTTray> usexiangqing(String storeID){
        List<WmsTTray> wmsTTrays = myService.seltray(storeID);
        return wmsTTrays;
    }
}
